package org.geektimes.configuration.microprofile.config.source;

import org.eclipse.microprofile.config.spi.ConfigSource;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public abstract class MapPropertiesSource implements ConfigSource {

    private final String name;

    private final int ordinal;

    /**
     * Java 系统属性最好通过本地变量保存，使用 Map 保存，尽可能运行期不去调整
     * -Dapplication.name=user-web
     */
    private Map<String, String> source;

    public MapPropertiesSource(String name, int ordinal) {
        this.name = name;
        this.ordinal = ordinal;
        this.source = getProperties();
    }

    public abstract void readProperties(Map properties) throws Throwable;

    @Override
    public Map<String, String> getProperties() {
        Map<String,String> configData = new HashMap<>();
        try {
            readProperties(configData);
        } catch (Throwable cause) {
            throw new IllegalStateException("准备配置数据发生错误",cause);
        }
        return Collections.unmodifiableMap(configData);
    }

    @Override
    public int getOrdinal() {
        return ordinal;
    }

    @Override
    public Set<String> getPropertyNames() {
        return source.keySet();
    }

    @Override
    public String getValue(String s) {
        return source.get(s);
    }

    @Override
    public String getName() {
        return name;
    }
}
